package com.kly.interview.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jd.platform.hotkey.client.callback.JdHotKeyStore;
import com.kly.interview.annotation.AuthCheck;
import com.kly.interview.common.BaseResponse;
import com.kly.interview.common.DeleteRequest;
import com.kly.interview.common.ErrorCode;
import com.kly.interview.common.ResultUtils;
import com.kly.interview.constant.UserConstant;
import com.kly.interview.exception.BusinessException;
import com.kly.interview.exception.ThrowUtils;
import com.kly.interview.model.dto.question.QuestionAddRequest;
import com.kly.interview.model.dto.question.QuestionEditRequest;
import com.kly.interview.model.dto.question.QuestionQueryRequest;
import com.kly.interview.model.dto.question.QuestionUpdateRequest;
import com.kly.interview.model.entity.Question;
import com.kly.interview.model.entity.User;
import com.kly.interview.model.vo.QuestionVO;
import com.kly.interview.service.QuestionService;
import com.kly.interview.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

import static com.kly.interview.constant.CommonConstant.TEN_TIME_TTL;
import static com.kly.interview.constant.QuestionConstant.QUESTION_DETAIL_KEY;

/**
 * 用户题目接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // region 增删改查

    /**
     * 创建用户题目
     *
     * @param questionAddRequest
     * @return
     */
    @PostMapping("/add")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest) {
        ThrowUtils.throwIf(questionAddRequest == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(questionService.addQuestion(questionAddRequest));
    }

    /**
     * 删除用户题目
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新用户题目（仅管理员可用）
     *
     * @param questionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        // 数据校验
        questionService.validQuestion(question, false);
        // 判断是否存在
        long id = questionUpdateRequest.getId();
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = questionService.updateById(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户题目（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 自动获取热点key
        String key = QUESTION_DETAIL_KEY + id;
        if (JdHotKeyStore.isHotKey(key)) {
            Object obj = JdHotKeyStore.get(key);
            if (obj != null) {
                return ResultUtils.success((QuestionVO) obj);
            }


        }

        // 查询redis形成多级缓存
        String cache = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(cache)) {
            return ResultUtils.success(JSONUtil.toBean(cache, QuestionVO.class));
        }
        // 防止缓存穿透
        ThrowUtils.throwIf("".equals(cache), ErrorCode.NOT_FOUND_ERROR);

        // 查询数据库
        Question question = questionService.getById(id);
        // 随机时间
        int expireTime = TEN_TIME_TTL + RandomUtil.randomInt(1, 10);
        // 缓存空值
        if (question == null) {
            stringRedisTemplate.opsForValue().set(key, "", expireTime, TimeUnit.MINUTES);
        }
        ThrowUtils.throwIf(question == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        QuestionVO questionVO = questionService.getQuestionVO(question, request);
        // 设置热点key
        JdHotKeyStore.smartSet(key, questionVO);
        // 判断是否是热key 缓存到redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(questionVO), expireTime, TimeUnit.SECONDS);

        return ResultUtils.success(questionVO);
    }

    /**
     * 分页获取用户题目列表（仅管理员可用）
     *
     * @param questionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest) {
        ThrowUtils.throwIf(questionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(questionService.listQuestionByPage(questionQueryRequest));
    }

    /**
     * 分页获取用户题目列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                               HttpServletRequest request) {

        // 根据热点参数限流 单ip限流
        String ip = request.getRemoteAddr();
        Entry entry = null;
        try {
            entry = SphU.entry("listQuestionVOByPage", EntryType.IN, 1, ip);
            // Your logic here.
            Page<Question> questionPage = questionService.listQuestionByPage(questionQueryRequest);
            // 获取封装类
            Page<QuestionVO> questionVOPage = questionService.getQuestionVOPage(questionPage, request);
            return ResultUtils.success(questionVOPage);
        } catch (Exception e) {
            // Handle request rejection.
            //     判断是不是业务异常
            if (!BlockException.isBlockException(e)) {
                Tracer.trace(e);
                return ResultUtils.error(ErrorCode.SYSTEM_ERROR);
            }
            //     判断是不是降级异常
            if (e instanceof DegradeException) {
                return handleFallback();
            }

            //     限流异常
            return ResultUtils.error(ErrorCode.TOO_MANY_REQUEST);
        } finally {
            if (entry != null) {
                entry.exit(1, ip);
            }
        }

    }

    // 返回本地数据或者空数据
    public BaseResponse<Page<QuestionVO>> handleFallback() {
        return ResultUtils.success(null);
    }

    /**
     * 分页获取当前登录用户创建的用户题目列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listMyQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(questionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Question> questionPage = questionService.listQuestionByPage(questionQueryRequest);
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 编辑用户题目（给用户使用）
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionEditRequest, question);
        // 数据校验
        questionService.validQuestion(question, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = questionEditRequest.getId();
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionService.updateById(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion


}
